package com.example.translation.service;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class BaiduTranslationService implements TranslationService {

	@Value("${baidu.translate.appid}")
	private String appId;

	@Value("${baidu.translate.api-key}")
	private String apiKey;

	@Value("${baidu.translate.secret-key}")
	private String secretKey;

//    private AipTranslate client;

	@PostConstruct
	public void init() {
		// 初始化AipTranslate客户端
//        client = new AipTranslate(appId, apiKey, secretKey);
//
//        // 可选：设置网络连接参数
//        client.setConnectionTimeoutInMillis(2000);
//        client.setSocketTimeoutInMillis(60000);
	}

	@Override
	public String translate(String text, String from, String to) throws Exception {
		// 调用百度翻译API https://fanyi-api.baidu.com/doc/21
//        JSONObject result = client.translate(text, from, to, null);
		JSONObject result = new JSONObject();
		// 检查是否有错误
		if (result.has("error_code")) {
			throw new Exception("翻译失败: " + result.getString("error_msg"));
		}

		// 解析翻译结果
		JSONArray translations = result.getJSONArray("trans_result");
		JSONObject translation = translations.getJSONObject(0);

		return translation.getString("dst");
	}
}
